//////////////////////////////////////////////////////////////////
// MattiseOS Kernel
// Date: 2008
// Author: Matthew Iselin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//////////////////////////////////////////////////////////////////

// Includes
#include <stdint.h>
#include <string.h>

// Functions

// counts the number of characters in a null-terminated string
size_t strlen( const char* str )
{
    size_t ret = 0;
	if(!str)
		return 0;
    while( *str++ != 0 ) ret++;
    return ret;
}

// copies two strings
char* strcpy( char* dest, const char* src )
{
	if(!dest || !src)
		return 0;
	while( *src )
		*dest++ = *src++;
	*dest = 0;
	return dest;
}

// compares two strings
int32_t strcmp( const char* str1, const char* str2 )
{
	if(!str1 || !str2)
		return -2; // hehe, terrible error code
	while( *str1 != 0 && *str2 != 0 )
	{
		if( *str1 < *str2 )
			return -1;
		else if( *str1 > *str2 )
			return 1;
		str1++;
		str2++;
	}
	return 0;
}

// compares two strings (using a byte count instead of zeroes)
int32_t strncmp( const char* str1, const char* str2, size_t count )
{
	if(!str1 || !str2)
		return -2; // hehe, terrible error code

	// same as strcmp, but loop through using count
	size_t i;
	for( i = 0; i < count; i++ )
	{
		if( *str1 < *str2 )
			return -1;
		else if( *str1 > *str2 )
			return 1;
		str1++;
		str2++;
	}
	return 0;
}

// appends one string to another
char* strcat( char* dest, const char* src )
{
	if(!dest || !src)
		return 0;

	// save the old dest pointer
	char* old = dest;

	// move to the end of dest
	while( *dest++ ); dest--;

	// start appending data
	while( *src )
		*dest++ = *src++;
	*dest = 0;

	// return the original pointer
	return old;
}

// finds a character within a string
int32_t find( const char* str, int8_t c, int32_t s, int32_t e )
{
	if(!str)
		return -1;

	// move through the substring
	int32_t i;
	for( i = s; i < e; i++ )
		if( str[i] == c )
			return i;
	return -1;
}
